import { Component, OnInit, Output, Input, EventEmitter, ViewChild, ElementRef, Renderer2 } from '@angular/core';
const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json' }) };
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';
import axios from 'axios';
import { Router } from '@angular/router';
import { NzModalRef, NzFormatEmitEvent, NzModalService, NzTreeComponent, NzTreeNodeOptions, NzMessageService, UploadFile } from 'ng-zorro-antd';
import { PagesService } from 'services/pages.service';
import { UtilService } from 'services/util.service';
import { RequestService } from 'services/request.service';
declare var layui: any;
declare var layer: any;
declare var $: any;

@Component({
  selector: 'app-tab-upload',
  templateUrl: './tab-upload.component.html',
  styleUrls: ['./tab-upload.component.scss']
})
export class TabUploadComponent implements OnInit {

  constructor(public interfaceService: PagesService, public utilService: UtilService, public request: RequestService, private elementRef: ElementRef, private renderer: Renderer2
    , private msg: NzMessageService) { }

  @Output() private outer = new EventEmitter();
  @Input() puc_msg: any;

  ngOnInit() {
  }

  /**
   * 模块下载
   */
  template_download(json) {
    this.interfaceService.postPage("/erp/common/file/filemodelderive", json).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
      if (data.code == 200) {
        axios({
          method: 'post',
          url: data.object.fileUrl,
          responseType: 'arraybuffer',
          data: json
        })
          .then(res => {
            // 假设 data 是返回来的二进制数据
            const datas = res.data
            const url = window.URL.createObjectURL(new Blob([datas], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }))
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', data.object.fileName + '.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
      } else {
        layer.msg(data.message);
      }
    }
    });
  }

  /**
   * 数据导出(excel)
   */
  data_output(json, url?) {
    url = url === undefined ? '/erp/system/docdtl/docdtlexportrequest' : url;
    this.interfaceService.postPage(url, json).subscribe((data: any) => {
      if (this.interfaceService.codeValidation(data)) {
      if (data.code == 200) {
        axios({
          method: 'post',
          url: data.object.fileUrl,
          responseType: 'arraybuffer',
          data: json
        })
          .then(res => {
            // 假设 data 是返回来的二进制数据
            const datas = res.data
            const url = window.URL.createObjectURL(new Blob([datas], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }))
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', data.object.fileName + '.xlsx')
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
      } else {
        layer.msg(data.message);
      }
    }
    });
  }



  isupload = false;
  upload_data = {}//上传自定义参数
  upload_show(json): void {
    this.upload_data = json
    this.isupload = true;
  }
  upload_guanbi(): void {
    this.isupload = false;
    this.FileList = []  //清除上传成功文件列表(此列表中文件不会自动删除，且手动删除时会再走一遍上传接口)
  }

  FileList = []

  /**
   * 上传前事件
   */
  beforeUpload = (file: File) => {
    const xls = file.type === 'application/vnd.ms-excel'; //csv和xls文件类型
    const xlsx = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; //xlsx文件类型
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!xls && !xlsx) {
      this.msg.error('上传文件类型只能是csv,xls,xlsx');
    } else if (!isLt2M) {
      this.msg.error('上传文件大小不能大于2M');
    }
    return xls && isLt2M || xlsx && isLt2M;
  }

  /**
   * 上传事件
   * @param param0 
   */
  handleChange({ file, fileList }): void {
    const status = file.status;
    if (status !== 'uploading') {
      if (file.response.code == 200) {
        this.msg.success(file.response.message);
        this.upload_guanbi();
        this.outer.emit(file.response.object)
      } else {
        this.msg.error(file.response.message);
      }
    }
    if (status === 'done') {
      // this.msg.success(`${file.name} 上传请求成功`);
    } else if (status === 'error') {
      this.msg.error(`${file.name} 上传请求失败`);
    }
  }


}
